<?php


namespace logicmodel;



use comservice\GetRedis;
use comservice\Response;
use datamodel\Users;
use EasyWeChat\Factory;
use logicmodel\award\Recommend;

class WxLogic
{
    private $config;
    public  $message='支付失败';
    public function __construct()
    {
        $this->config = [
            'app_id' => config('site.wx_app_id'), // APP APPID
            'secret' => config('site.wx_app_secret'),
            'mch_id' => config('site.wx_mch_id'),
            'key' => config('site.wx_mch_key'),
            'cert_path' => config('site.wx_client_cert'), // optional，退款等情况时用到
            'key_path' => config('site.wx_client_pem'),// optional，退款等情况时用到
        ];
    }

    /**
     * APP支付
     * @param $order_num
     * @param $body
     * @param $amount
     * @param $notify_url
     * @return array|bool
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function  appPay($order_num,$body,$amount,$notify_url){
        $payConfig = $this->config;
        $payConfig['notify_url'] = $notify_url;
        $app = Factory::payment($payConfig);
        $order = [
            'body' => $body,
            'out_trade_no' => $order_num,
            'total_fee' => bcmul($amount,100,0),
            'trade_type' => 'APP', // 请对应换成你的支付方式对应的值类型
        ];
        $result = $app->order->unify($order);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] != 'FAIL'){
            $prepay_id = $result['prepay_id'];
            return $app->jssdk->appConfig($prepay_id);
        }
        return false;
    }
    /**
     * 企业付款到个人
     * @param $order_num
     * @param $open_id
     * @param $amount
     * @return bool|mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function draw($order_num,$open_id,$amount){
        try {
            $payConfig = $this->config;
            $payConfig['mch_id'] = config('site.wx_draw_mch_id');
            $payConfig['key'] = config('site.wx_draw_mch_key');
            $app = Factory::payment($payConfig);
            $result = $app->transfer->toBalance(
                [
                    'partner_trade_no' => $order_num, // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
                    'openid' => $open_id,
                    'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
                    'amount' => bcmul($amount, 100, 0),
                    'desc' => '佣金提现', // 企业付款操作说明信息。必填
                ]
            );
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') return $result['payment_no'];
            $this->message = $result['err_code_des'];
            return false;
        }catch (\Exception $e){
            return  false;
        }
    }

    /**
     * 微信公众号授权
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function  auth($code){
        $config = [
            'app_id' => config('site.wx_global_app_id'), // APP APPID
            'secret' => config('site.wx_global_app_secret'),
        ];
        $app =  Factory::officialAccount($config);
        $user = $app->oauth->user();
        $open_id = $user->getId();
        $usersData = new Users();
        $user_id =  $usersData->where(['is_del'=>0,'wx_open_id'=>$open_id])->value('id');
       if(empty($user_id)){
           $account = (new WalletLogic())->newAccount();
           $nick_name = $user->getNickname();
           $parentInfo =  $usersData->where(['id'=>1])->find();
           $pid = $parentInfo['id'];
           $data['head_image'] = $user->getAvatar();
           $data['nick_name'] = $nick_name;
           $data['pid'] = $pid;
           $data['upid'] = $pid;
           $data['uuid'] = uuid();
           $data['create_time'] = date('Y-m-d H:i:s');
           $data['parent_member'] = $parentInfo['phone'];
           $data['wx_open_id'] = $open_id;
           $data['is_wx_auth'] = 1;
           if($account !== false){
               $data['wallet_address'] = $account['address'];
               $data['wallet_private_key'] = $account['private_key'];
           }
           $user_id =  $usersData->insertGetId($data);
           if(empty($user_id)) return  Response::fail('授权失败');
             award($user_id);
           $remark = '推荐会员' . $nick_name . '注册奖励';
           (new Recommend())->award($pid,$user_id,$remark);
       }
        //判断是否绑定过手机号
        $app_token = uniqueNum();
        $redis = GetRedis::getRedis();
        $redis->setItem('app_'.$app_token,$user_id);
        $usersData->updateByWhere(['id'=>$user_id],['app_token'=>$app_token,'login_time'=>date('Y-m-d H:i:s')]);
        return  Response::success('success',['app_token'=>$app_token]);
    }

    /**
     * 微信授权
     * @param $userInfo
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function userAuth($userInfo){
        if($userInfo['is_wx_auth'] == 1) return Response::success('授权成功');
        $config = [
            'app_id' => config('site.wx_app_id'), // APP APPID
            'secret' => config('site.wx_app_secret'),
        ];
        $app =  Factory::officialAccount($config);
        $user = $app->oauth->user();
        $open_id = $user->getId();
        $result = (new Users())->updateByWhere(['id'=>$userInfo['id']],['wx_open_id'=>$open_id,'is_wx_auth'=>1]);
        if($result) return Response::success('授权成功');
        return Response::fail('授权失败');
    }

    /**
     * 微信支付
     * @param $order_num
     * @param $body
     * @param $amount
     * @param $notify_url
     * @param $openid
     * @return array|bool|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function pay($order_num,$body,$amount,$openid,$notify_url){
        $config = [
            'app_id' => config('site.wx_global_app_secret'), // 小程序 APPID
            'mch_id' => config('site.wx_mch_id'),
            'key' => config('site.wx_mch_key'),
            'cert_path' => config('site.wx_client_cert'), // optional，退款等情况时用到
            'key_path' => './cert/apiclient_key.pem',// optional，退款等情况时用到
        ];
        $config['notify_url'] = $notify_url;
        $app = Factory::payment($config);
        $order = [
            'body' => $body,
            'out_trade_no' => $order_num,
            'total_fee' => bcmul($amount,100,0),
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid'=>$openid,
        ];
        $result = $app->order->unify($order);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] != 'FAIL'){
            $prepay_id = $result['prepay_id'];
            return $app->jssdk->bridgeConfig($prepay_id,false);
        }
        return false;
    }
}